const comment = require("../../models/comment");

module.exports = (app, router) => {
  const Article = require("../../models/article");
  const Comment = require("../../models/comment");
  const Counts = require("../../models/counts");
  const Tools = require("../../models/tools");
  const { pagingResult, requestResult } = require("../../plugins/index.js");
  router.post("/article", async (req, res) => {
    let page = req.body.page || 1;
    let size = req.body.size || 10;
    let db = Article.find().populate("articleType");
    let data = await pagingResult(db, page, size);

    res.send(requestResult(data));
  });
  router.get("/article/:id", async (req, res) => {
    let id = req.params.id;
    await Article.findOneAndUpdate(
      {
        id: id,
      },
      {
        $inc: { read: 1 },
      },
      {
        new: true,
      }
    );
    let data = await Article.findOne({ id: id }).populate("articleType");
    res.send(requestResult(data));
  });
  //评论
  router.post("/comment", async (req, res) => {
    const commentID = await Counts.findOneAndUpdate(
      {
        name: "comment",
      },
      {
        $inc: { id: 1 },
      },
      {
        new: true,
      }
    );
    if (commentID) {
      req.body.id = commentID;
    } else {
      const data = {
        name: "comment",
        id: 1,
      };
      const count = await Counts.create(data);
      req.body.id = count.id;
    }
    console.log(req.body);
    const result = await Comment.create(req.body);
    res.send(requestResult(result));
  });
  //获取评论
  router.get('/comment', async(req, res) => {
    const data = await Comment.find({articleId: req.query.id || -1})
    res.send(requestResult(data))
  })
  router.post("/findOneComment", async (req, res) => {
    const data = await Comment.find();
    res.send(requestResult(data));
  });

  router.get("/like", async (req, res) => {
    let id = req.query.id;
    let data = await Article.updateOne(
      {
        id: id,
      },
      {
        $inc: { like: 1 },
      }
    );
    res.send(requestResult(data));
  });

  router.get("/tools", async (req, res) => {
    let data = await Tools.find();
    res.send(requestResult(data));
  });
  app.use("/web/api", router);
};
